﻿using System;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

namespace UserRedirect.Layouts.InfoSystems
{
    public partial class RedirectUsers : LayoutsPageBase
    {
        override protected void OnInit(EventArgs e)
        {
            // Do Base OnInit
            base.OnInit(e);

            // Load Existing Mappings
            LoadExistingMappings();
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get the Site
            using (SPSite site = new SPSite(Site.ID))
            {
                // Get the web
                using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                {
                    // Validate the page request to avoid 
                    // any malicious posts. 
                    if (Request.HttpMethod == "POST")
                        SPUtility.ValidateFormDigest();

                    // Determine whether the user has full control 
                    // over the site. If not, redirect the user 
                    // to the access-denied page. 
                    if (web.DoesUserHavePermissions(SPBasePermissions.ManageWeb))
                    {
                        // Ensure this is not a Post Back
                        if (!IsPostBack)
                        {
                            // Load Dropdown list
                            LoadSharePointGroups();
                        }
                    }
                    else
                    {
                        // No rights so boot them
                        SPUtility.HandleAccessDenied(new Exception("You are not authorized to access this page."));
                    }
                }
            }
        }

        private void LoadSharePointGroups()
        {
            // Get the Site
            using (SPSite site = new SPSite(Site.ID))
            {
                // Get the web
                using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                {
                    // Get Site Groups                    
                    SPGroupCollection Groups = web.SiteGroups;

                    // Add Groups to Dropdown
                    foreach (SPGroup Group in Groups)
                    {
                        // Get Redirect User List
                        SPList list = web.Lists["Redirect Users"];

                        // Get List Items
                        SPListItemCollection listitems = list.Items;

                        // Loop through Items
                        bool GroupFound = false;
                        foreach (SPListItem listitem in listitems)
                        {
                            // Check if group is already in the list
                            string ListGroup = listitem[new Guid("{04DC682E-F36D-48D3-A958-0FF699921F7F}")].ToString();

                            if (ListGroup == Group.Name)
                            {
                                GroupFound = true;
                                break;
                            }
                        }
                        
                        // Add if group not found
                        if (!GroupFound)
                        {
                            this.SharePointGroup.Items.Add(Group.Name);
                        }
                    }

                    // Check if any groups were added
                    if (this.SharePointGroup.Items.Count > 0)
                    {
                        // Groups were added
                        this.SharePointGroup.Visible = true;
                        this.SharePointGroupLable.Visible = false;
                    }
                    else
                    {
                        // No Groups were added
                        this.SharePointGroup.Visible = false;
                        this.SharePointGroupLable.Visible = true;
                    }
                }
            }
        }

        private void LoadExistingMappings()
        {
            try
            {
                // Get the Site
                using (SPSite site = new SPSite(Site.ID))
                {
                    // Get the web
                    using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                    {
                        // Get Redirect User List
                        SPList list = web.Lists["Redirect Users"];

                        // Get List Items
                        SPListItemCollection listitems = list.Items;

                        // Loop through Items
                        foreach (SPListItem listitem in listitems)
                        {
                            // Create Table Row
                            TableRow TR = new TableRow();

                            // Add Style to Row
                            TR.Attributes.Add("class", "RedirectUser-Row");

                            // Create Table Cells
                            TableCell TD_RemoveLink = new TableCell();
                            TableCell TD_SharePointGroup = new TableCell();
                            TableCell TD_LandingPage = new TableCell();

                            // Add Style to Cells
                            TD_RemoveLink.Attributes.Add("class", "RedirectUser-Cell");
                            TD_SharePointGroup.Attributes.Add("class", "RedirectUser-Cell");
                            TD_LandingPage.Attributes.Add("class", "RedirectUser-Cell");

                            // Create Delete Button
                            LinkButton LB = new LinkButton();
                            LB.ID = "Button_" + listitem.ID.ToString();
                            LB.Text = "[Delete]";
                            LB.CausesValidation = false;
                            LB.Click += new EventHandler(DeleteButton_Click);

                            // Populate Table Cells
                            TD_RemoveLink.Controls.Add(LB);
                            TD_SharePointGroup.Text = listitem[new Guid("{04DC682E-F36D-48D3-A958-0FF699921F7F}")].ToString();
                            TD_LandingPage.Text = listitem[new Guid("{5F86CF95-31A3-48FE-83AD-F74D26C514C5}")].ToString();

                            // Add Cells to Row
                            TR.Controls.Add(TD_RemoveLink);
                            TR.Controls.Add(TD_SharePointGroup);
                            TR.Controls.Add(TD_LandingPage);

                            // Add Row to Placeholder
                            this.RedirectUserRows.Controls.Add(TR);
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("InfoSystems", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }
        }

        void DeleteButton_Click(object sender, EventArgs e)
        {
            // Get List Item ID
            string ButtonName = ((LinkButton)sender).ID;
            int ItemID = Convert.ToInt32(ButtonName.Replace("Button_", ""));

            try
            {
                // Get the Site
                using (SPSite site = new SPSite(Site.ID))
                {
                    // Get the web
                    using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                    {
                        // Get Redirect User List
                        SPList list = web.Lists["Redirect Users"];

                        // Get List Item
                        SPListItem listitem = list.GetItemById(ItemID);

                        // Delete the item
                        listitem.Delete();
                    }
                }
            }

            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("InfoSystems", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }

            finally
            {
                // Reload Page
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void AddButton_Click(object sender, EventArgs e)
        {
            // only process if the form is valid
            if (IsValid)
            {
                try
                {
                    // Get the Site
                    using (SPSite site = new SPSite(Site.ID))
                    {
                        // Get the web
                        using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                        {
                            // Get Redirect User List
                            SPList list = web.Lists["Redirect Users"];

                            // Add entry to list
                            SPListItem listitem = list.Items.Add();

                            // Set properties
                            listitem[new Guid("{04DC682E-F36D-48D3-A958-0FF699921F7F}")] = this.SharePointGroup.SelectedValue;
                            listitem[new Guid("{5F86CF95-31A3-48FE-83AD-F74D26C514C5}")] = this.LandingPage.Text;

                            // Update the list item
                            listitem.Update();
                        }
                    }
                }

                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("InfoSystems", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
                }

                finally
                {
                    // Reload Page
                    Response.Redirect(Request.RawUrl);
                }
            }
        }
    }
}
